package edu.calpoly.csc.coursebook.business;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import edu.calpoly.csc.coursebook.business.beans.FinderBean;

public class FinderValidator implements Validator
{
   private static final int MIN_LENGTH = 1;
   private static final int MAX_LENGTH = 4096;
   
   /** Logger for this class and sublcasses */
   protected final Log log = LogFactory.getLog(this.getClass());
   
   public boolean supports(Class clazz)
   {
      return clazz.equals(FinderBean.class);
   }

   public void validate(Object target, Errors errors)
   {
      FinderBean fb = (FinderBean) target;
      if (null == fb)
      {
	 errors.rejectValue("interests", "error.not-specified", null, "Value required.");
      }
      else
      {
	 log.info("Validating with " + fb + ": " + fb.getInterests());
	 int len = fb.getInterests().length();
	 
	 if (len >= FinderValidator.MAX_LENGTH)
	 {
	    errors.rejectValue("interests", "error.too-long", 
		  new Object[] {MAX_LENGTH}, "Too many interests");
	 }
	 if (len < FinderValidator.MIN_LENGTH)
	 {
	    errors.rejectValue("interests", "error.too-short", 
		  new Object[] {MIN_LENGTH}, "Not enough interests");
	 }
      }
   }
}
